package spring.module.zipfilter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import lombok.experimental.UtilityClass;

/**
 * 压缩工具
 * 
 * @author Lucky Yang
 */
@UtilityClass
public class GZIPUtils {
    public static final Charset GZIP_ENCODE_UTF_8 = StandardCharsets.UTF_8;

    /**
     * 压缩字符串， 默认utf-8 字符集
     * 
     * @param str
     * @return
     */
    public byte[] compress(String str) {
        return compress(str, GZIP_ENCODE_UTF_8);
    }

    /**
     * 解压成字符串
     * 
     * @param bytes
     * @return
     * @throws IOException
     */
    public String uncompressToString(byte[] bytes) throws IOException {
        byte[] result = uncompress(bytes);
        return new String(result, GZIP_ENCODE_UTF_8);
    }

    /**
     * 压缩字符串
     * 
     * @param str
     * @param encoding
     * @return
     */
    public byte[] compress(String str, Charset encoding) {
        if (str == null || str.length() == 0) {
            return new byte[0];
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
                GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(str.getBytes(encoding));
            gzip.finish();      // 必须的，不然解压时有异常：java.io.EOFException: Unexpected end of ZLIB input stream
            return out.toByteArray();
        } catch (IOException e) {
            throw new ZipException(e);
        }
    }

    /**
     * 解压
     * 
     * @param bytes
     * @return
     */
    public byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return new byte[0];
        }

        int bufferSize = 256;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                GZIPInputStream ungzip = new GZIPInputStream(in, bufferSize)) {
            
            byte[] buffer = new byte[bufferSize];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
            throw new ZipException(e);
        }
    }
}
